﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DrawVisualDemo01
{
    public class CusCanvas : Canvas
    {
        /// <summary>
        /// canvas画布里面的所有元素
        /// </summary>
        List<Visual> visuals = new List<Visual>();

        protected override Visual GetVisualChild(int index)
        {
            return visuals[index];
        }

        protected override int VisualChildrenCount => visuals.Count;

        /// <summary>
        /// 填充色
        /// </summary>
        Brush brush = new SolidColorBrush(Colors.Red);

        /// <summary>
        /// 画笔外边框颜色
        /// </summary>
        Brush brushPen = new SolidColorBrush(Colors.Blue);

        public void DrawRectangle(System.Windows.Point point)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            if (drawingVisual != null)
            {
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                Pen pen = new Pen(brushPen, 1);
                drawingContext.DrawRectangle(brush, pen, new Rect(point, new System.Windows.Size(50, 50)));
                drawingContext.Close();
                AddVisual(drawingVisual);
            }
        }

        /// <summary>
        /// 添加一个Visual到画布
        /// </summary>
        /// <param name="visual"></param>
        public void AddVisual(Visual visual)
        {
            base.AddLogicalChild(visual);
            base.AddVisualChild(visual);
            visuals.Add(visual);
        }
    }
}
